<?php
/**
* ContentSubscription - Restrict access to content
* @version 2.0
* @package AkoComment
* @copyright (C) 2006 by Sergey Romanov - All rights reserved!
**/

defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

$_MAMBOTS->registerFunction( 'onPrepareContent', 'jcsCheckRights' );

        
function jcsCheckRights($published, &$row, &$params, $page=0 ) {

    global $database, $mainframe, $option, $task, $mosConfig_lang, 
           $mosConfig_absolute_path, $mosConfig_live_site, $my, $Itemid;

    error_reporting(0);
    @session_start();
    //echo $mosConfig_live_site.$_SERVER['REQUEST_URI'].'<BR>'; 
    //echo $_SESSION['jcs_access_url']; 
    //exit;
    if($_SESSION['jcs_access_url'] == $mosConfig_live_site.$_SERVER['REQUEST_URI'])
        unset($_SESSION['jcs_access_url']);
    
    global $database;

    $query = "SELECT id"
    . "\n FROM #__mambots"
    . "\n WHERE element = 'jcontentsubscription.content'"
    . "\n AND folder = 'content'"
    ;
    $database->setQuery( $query );
    $id     = $database->loadResult();
    $mambot = new mosMambot( $database );
    $mambot->load( $id );
    $botParams = new mosParameters( $mambot->params );
    if($botParams->def('se'))
    {
        $BOTS = ARRAY(
        'googlebot','mediapartners-google', 'yahoo-verticalcrawler', 
        'yahoo! slurp', 'yahoo-mm', 'inktomi', 'slurp', 'iltrovatore-setaccio',
        'fast-webcrawler', 'msnbot', 'ask jeeves', 'teoma', 'scooter', 'psbot', 
        'openbot', 'ia_archiver', 'almaden', 'baiduspider', 'zyborg', 'gigabot', 
        'naverbot', 'surveybot', 'boitho.com-dc', 'objectssearch', 'answerbus',
        'sohu-search'
         );
        foreach($BOTS AS $bot)
        {
            if(
              stristr(
                strtolower($_SERVER['HTTP_USER_AGENT'])
                , $bot
              )
            ) 
            return;
        }
    }

    if (file_exists( $mosConfig_absolute_path.'/components/com_jcs/languages/'.$mosConfig_lang.'.php' ))
        include_once( $mosConfig_absolute_path.'/components/com_jcs/languages/'.$mosConfig_lang.'.php' );
    else
        require_once( $mosConfig_absolute_path.'/components/com_jcs/languages/english.php' );
    

    $task =  mosGetParam( $_REQUEST, 'task', false);
    $return = true;
    if($task != 'view')
    {
        $row->text = preg_replace("/{JCSBOT USER=[^}]+}/iU", "", $row->text);
        $row->text = preg_replace("/{JCSBOT SUBSCRIPTION=[^}]+}/iU", "", $row->text);
        $return = false;
        //return;
    }       
    
    // Firs start to check categry restrict
    $query = "SELECT id, category "
    . "\n FROM #__jcs_plans WHERE published = 1 AND `type_category` = 1 AND `category` != ''"
    ;
    $database->setQuery( $query );
    $categories = $database->loadObjectList();
    
    $categories = jcsGetCategories($categories);
    
    if($categories && in_array($row->catid, $categories))
    {
        //print_r($categories);
        //return;
        if(!$my->id)
        {
            if($return) jcsRestrictC($row, $params, $JCS_MSG_2);
            jcsMarkTitle($row, $botParams);
            return;
        }
        $sql = "
             SELECT u.subscription_id, u.id, s.`category`, u.access_count, u.access_limit 
               FROM #__jcs_user_subscr AS u
          LEFT JOIN #__jcs_plans AS s ON s.id = u.subscription_id 
              WHERE u.user_id = {$my->id} 
                AND u.extime > NOW()
                AND u.ctime < NOW() 
                AND u.published = 1
                AND s.`type_category` = 1 
           ORDER BY u.ctime DESC";
                //echo $sql;
        $database->setQuery( $sql );
        $rows1 = $database->loadObjectList();
        $uscat = jcsGetCategories($rows1);
        //print_r($uscat);
        //return;
        if(!in_array($row->catid, $uscat))
        {
            if($return) jcsRestrictC($row, $params, $JCS_MSG_2);
            jcsMarkTitle($row, $botParams);
            return;
        }
        foreach($rows1 AS $row1)
        {
            if(($row1->access_limit > 0) && ($row1->access_count >= $row1->access_limit))
            {
                if($return) jcsRestrictC($row, $params, $JCS_MSG_2);
                jcsMarkTitle($row, $botParams);
                return;
            }
            else
            {
//echo $row1->subscription_id;
jcsUpdate('type_category', $row1->subscription_id);
            }
        }
    }
    
    // test user id based subscription
    if(preg_match("/{JCSBOT USER=([\d,]+)}/iU", $row->text, $matches))
    {
        //echo "dfhgfhdf";
        $row->text = preg_replace("/{JCSBOT USER=[^}]+}/iU", "", $row->text);
        $ids = explode(",",$matches[1]);
        //print_r($matches);
        //print_r($ids);
        //exit;
        if(!in_array($my->id, $ids) || !$my->id)
        {
            if($return) jcsRestrictC($row, $params, $JCS_MSG_2);
            jcsMarkTitle($row, $botParams);
            return;
        }
        $sql = "
             SELECT u.subscription_id, u.`id`, u.access_count, u.access_limit   
               FROM #__jcs_user_subscr AS u
          LEFT JOIN #__jcs_plans AS s ON s.id = u.subscription_id 
              WHERE u.user_id = {$my->id} 
                AND u.extime > NOW()
                AND u.ctime < NOW() 
                AND u.published = 1 
                AND s.`type_user` = 1 
           ORDER BY u.ctime DESC";
        $database->setQuery( $sql );
        $rows2 = $database->loadObjectList();
        if(count($rows2) <= 0)
        {
            if($return) jcsRestrictC($row, $params, $JCS_MSG_2);
            jcsMarkTitle($row, $botParams);
            return;
        }
        foreach($rows2 AS $row2)
        {
            if(($row2->access_limit > 0) && ($row2->access_count >= $row2->access_limit))
            {
                if($return) jcsRestrictC($row, $params, $JCS_MSG_2);
                jcsMarkTitle($row, $botParams);
                return;
            }
            else
            {
                jcsUpdate('type_user', $row2->subscription_id);
            }
        }
    }
    
    //test suscription based
    if(preg_match("/{JCSBOT SUBSCRIPTION=([\d,]+)}/iU", $row->text, $matches))
    {
        
        $row->text = preg_replace("/{JCSBOT SUBSCRIPTION=[^}]+}/iU", "", $row->text);
        //print_r($matches); echo "111111111111111"; return;
        if(!$my->id)
        {
            if($return) jcsRestrictC($row, $params, $JCS_MSG_2);
            jcsMarkTitle($row, $botParams);
            return;
        }
        
        $sql = "
             SELECT u.subscription_id, u.`id`, u.access_count, u.access_limit   
               FROM #__jcs_user_subscr AS u
          LEFT JOIN #__jcs_plans AS s ON s.id = u.subscription_id 
              WHERE u.user_id = {$my->id} 
                AND u.extime > NOW()
                AND u.ctime < NOW() 
                AND u.published = 1 
                AND s.id IN ({$matches[1]})
                AND s.`type_article` = 1 
           ORDER BY u.ctime DESC";
                
        $database->setQuery( $sql );
        $rows3 = $database->loadObjectList();
        
        if(count($rows3) <= 0)
        {
            if($return) jcsRestrictC($row, $params, $JCS_MSG_2);
            jcsMarkTitle($row, $botParams);
            return;
        }
        foreach($rows3 AS $row1)
        {
            if(($row1->access_limit > 0) && ($row1->access_count > $row1->access_limit))
            {
                if($return) jcsRestrictC($row, $params, $JCS_MSG_2);
                jcsMarkTitle($row, $botParams);
                return;
            }
            else
            {
                jcsUpdate('type_article', $row1->subscription_id);
            }
        }
    }
}

function jcsMarkTitle(&$row, $param)
{
    global $Itemid;
    //echo "dddddd";
    if($param->def('mark') == 0) return;
    $sign = $param->def('pic');
    $img = sprintf('<img src="%s" alt="Subscribe" border="0" align="absmiddle" class="jcslock" /> %s', $sign, $param->def('pic_text'));
    if($param->def('link') == 1)
    {
        $img = sprintf('<a href="%s">%s</a>', 
        sefRelToAbs('index.php?option=com_jcs&amp;task=add&amp;&Itemid='.$Itemid), $img );
    }
    switch($param->def('mark_type'))
    {
        case 0:
          $row->title = $img . ' ' . $row->title;
        break;

        case 1:
          $row->title .= ' '.$img;
        break;

        case 2:
          $class = '<style type="text/css">.jcslock{float:left}</style>';
          $row->text = $class.$img . ' ' . $row->text;
        break;

        case 3:
          $row->text .= ' <BR>'.$img;
        break;
    }
    return $row;
}

if(!defined('JCS_UPDATE_F'))
{
    define('JCS_UPDATE_F', 1);
    function jcsUpdate($type, $id = FALSE)
    {
        global $my, $database;
        
        $sql = "
            UPDATE #__jcs_user_subscr AS u, #__jcs_plans AS s 
               SET u.access_count = u.access_count + 1 
             WHERE u.subscription_id = s.id 
               AND s.$type = 1 
               AND u.user_id = {$my->id}
        ";
        $sql = "
            UPDATE #__jcs_user_subscr AS u, #__jcs_plans AS s 
               SET u.access_count = u.access_count + 1 
             WHERE u.subscription_id = s.id 
               AND s.$type = 1 ".
              ($id ? " AND u.subscription_id = '{$id}'" : "")
              ." AND u.user_id = {$my->id}
        ";
        $database->setQuery( $sql );
        $database->query();
        //echo $sql;
//echo $database->stderr();
        //echo $database->inserid();
    }
}

function jcsGetCategories($array)
{
    if(count($array) > 0)
    {
        $restrict = array();
        foreach($array AS $arr)
        {
            $restrict = array_merge($restrict, explode(",", $arr->category));
        }
        $restrict = array_flip($restrict);
        $restrict = array_flip($restrict);
        return $restrict;
    }
    return FALSE;
}

function jcsRestrictC(&$row, &$params, $msg)
{
    global $database, $mainframe, $option, $task, $mosConfig_lang, 
           $mosConfig_absolute_path, $mosConfig_live_site, $my, $Itemid;

    $url = mosGetParam( $_SERVER, 'REQUEST_URI', null );
    if ( strpos($url, 'http:') !== 0 && strpos($url, 'https:') !== 0 ) {
        if (strpos($url, '/') !== 0) {
            $url = '/'. $url;
        }
        $url = mosGetParam( $_SERVER, 'HTTP_HOST', null ) . $url;
        if ( isset( $_SERVER['HTTPS'] ) && ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] != 'off' ) ) {
            $url = 'https://'. $url;
        } else {
            $url = 'http://'. $url;
        }
    }
  
    @session_start();
    $_SESSION['jcs_access_url'] = $url;

    mosRedirect(sefRelToAbs($mosConfig_live_site."/index.php?option=com_jcs&task=add&Itemid=".$Itemid));

}
?>